<!--练习模式下，只要有内容既是已做了的-->
<!--考试模式倒计时本地保存-->

<script setup>
import {ElMessage, ElMessageBox} from 'element-plus'
import ListApis from '@/apis/list';
import QuestionApis from '@/apis/question';
import useLocalStore from '@/stores/local';
import {computed} from 'vue';
import {getCurrentInstance} from 'vue'
import PaperApis from '@/apis/paper.js'
import {encrypt} from '@/utils/jsencrypt.js'
import {useRoute, useRouter} from "vue-router";
import useUserStore from "@/stores/user.js";
import CommonQuestion from "@/components/common/CommonQuestion.vue";
import NoteApis from "@/apis/note.js";
import {signAndTimestamp} from '@/utils/jsencrypt.js'

let exitAction = 'url'
const showLeft = ref(true)
const loading = ref(false)
// 状态显示权重 :当前>标记>(已答|未答)
const questionStatusList = [{current: '当前', done: '已答', notDone: '未答', noted: '标记'}]
// 单选多选答案与参考答案对比，其中多选答案排序后循环判断所有或者转字符串对比
// answerStatus:'done','notDone'

const anotherMyAnswerCards = ref([]);
const questionList = ref([])
const questionTypeMap = ref({})
const questionMeta = ref({})
const collapse = ref(['name'])
const localStore = useLocalStore()
let generatePaper = null;

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const qCount = ref(0)
const common = ref(null)
const now = new Date().getTime();


const currentIndex = ref(null)
const questionData = ref(null)
const examTime = ref(0)
const firstTypeMap = {
  1: 'singleChoice',
  2: 'multipleChoice',
  3: 'judgement',
  4: 'fill',
  5: 'text',
  6: 'combination',
  7: 'indefiniteMultipleChoice'
}
const ccNum = ref(0);
if (route.query.cc) {
  ccNum.value = Number(route.query.cc)
}
const currentQuestion = computed(() => {
  if (currentIndex.value) {
    return questionData.value.content[currentIndex.value[0]].qs[currentIndex.value[1]];
  }
})
// 可为null和{}
const currentOptionsStatus = computed(() => {
  return {}
})

async function init() {
  let promise;
  if(route.query.recordId){
    promise= Promise.resolve({
      data: {
        id: route.query.recordId,
        examTime: Number(route.query.examTime),
        qcount: Number(route.query.qcount),
        seconds:60
      }
    })
  }else {
    promise=PaperApis.generateRecords(null, {
      params: {
        industryCode: route.query.industryCode,
        examId: route.query.examId,
        categoryId: route.query.categoryId,
        paperId: route.query.id,
        // recordsId:detail.value.id,
        columnId: route.query.columnId,
        result: false,
        practiceModel: false
      }, headers: {
        'content-type': 'application/x-www-form-urlencoded'
      }
    });
  }

  await promise.then(res => {
    generatePaper = res.data
    // 生成试题集合
    ListApis.questionCollection(encrypt(JSON.stringify({
      collectionType: 'paper',
      industryCode: route.query.industryCode,
      examId: route.query.examId,
      categoryId: route.query.categoryId,
      columnId: route.query.columnId,
      id: res.data.id,
      true: false
    }))).then(res1 => {
      // 这里倒计时前端做，因为后端没记录
      // 开始显示倒计时,如果是上次做过的，则从本地拿取时间，否则重新计时
      if (res.data.seconds) {
        //   seconds是保存时填入的字段
        //   如果做过，从本地拿取，如果没有拿到，则从现在开始，并重新保存到本地
        const examTimeObj = localStore.getExamTime({
          paperId: route.query.id,
          recordsId: res1.data.id
        });
        if (examTimeObj) {
          examTime.value = examTimeObj.startTime + res.data.examTime * 60 * 1000
        } else {
          examTime.value = Date.now() + res.data.examTime * 60 * 1000
          localStore.addExamTime({
            startTime: new Date().getTime(),
            paperId: route.query.id,
            recordsId: res1.data.id
          })
        }
      } else {
        examTime.value = Date.now() + res.data.examTime * 60 * 1000
        //  如果没做过。存入本地
        localStore.addExamTime({
          startTime: new Date().getTime(),
          paperId: route.query.id,
          recordsId: res1.data.id
        })
      }


      let num = 0
      res1.data.content.forEach(item => {
        item.qs.forEach(e => {
          num++
          if (e.record) {
            // 如果是填空题
            if (e.firstType == 4) {
              let array = e.record.as.split(' ')
              for (let i = 0; i < array.length; i++) {
                e['answer' + i] = array[i]
              }
              e.answer = e.record.as
              e.lockAnswer = e.record.as;
            } else {
              // 答案是json字符串格式,答案不存在的情况是没做
              if (e.record.as) {

                try{
                  e.answer = JSON.parse(e.record.as)
                  e.lockAnswer = JSON.parse(e.record.as);
                }catch (error){
                  e.answer = e.record.as
                  e.lockAnswer = e.record.as;
                }
              }
            }
          } else {
            // 如果是填空题
            if (e.firstType == 4) {
              for (let i = 0; i < e.quOption.length; i++) {
                e['answer' + i] = ''
                e.answer = ''
                e.lockAnswer = ''
              }
            } else {
              e.answer = [1, 3, 5].includes(e.firstType) ? '' : [];
              e.lockAnswer = [1, 3, 5].includes(e.firstType) ? '' : [];
            }

          }
          e.num = num;
          e.current = num == 1;
          e.answerStatus = e.record ? 'done' : 'notDone';
          e.isTrue = e.record ? e.record.rt : false
          e.note = ''
          // e.noted=e.collect

          // 做题时间和收藏时间
          e.time = 0
          if (e.collect) {
            if (!route.query.cc) {
              ccNum.value++
            }
          }
          e.notedTime = e.collect ? 1 : 0
        })
      })
      questionData.value = res1.data
      currentIndex.value = [0, 0]
      qCount.value = num;
    });
  }).catch((err) => {
    if (err.code == 104) {
      exitAction = 'force'
      ElMessage('3秒后返回')
      setTimeout(() => {
        router.go(-1)
      }, 3000)
      return
    }
  })
}

async function submitThis() {
}

function changeCurrent(i, j) {
  const [index1, index2] = currentIndex.value
  questionData.value.content[index1].qs[index2].current = false
  questionData.value.content[i].qs[j].current = true
  currentIndex.value = [i, j]
}

function toggle() {
  showLeft.value = !showLeft.value
}

function changeCheckbox(arr) {
  if (currentQuestion.value.lockAnswer.length > 0) return;
  currentQuestion.value.time = new Date().getTime()

  if (arr.length) {
    currentQuestion.value.answerStatus = 'done'
  } else {
    questionData.value.lastId =null
    currentQuestion.value.answerStatus = 'notDone'
    a:for (let i of questionData.value.content) {
      for (let j of i.qs) {
        if (j.answerStatus == 'done') {
          questionData.value.lastId = j.id;
          break a;
        }
      }
    }
  }
}

function changeRadio(val) {
  if (currentQuestion.value.lockAnswer.length > 0) return;
  currentQuestion.value.time = new Date().getTime()
  questionData.value.lastId = currentQuestion.value.id;
  currentQuestion.value.answerStatus = 'done'
}

function toggleNote() {
  if (!currentQuestion.value.collect) {
    QuestionApis.collectQuestion({
      industryCode: route.query.industryCode,
      examId: route.query.examId,
      categoryId: route.query.categoryId,
      // industryName: userStore.selectCategory.industryName,
      // examName: userStore.selectCategory.examName,
      // categoryName: userStore.selectCategory.categoryName,
      columnId: route.query.columnId,
      qid: currentQuestion.value.id,
      true: true,
      recordsType: 'paperRecordPaperLibrary',
      data: {
        qt: currentQuestion.value.firstType,
        // qt: firstTypeMap1[currentQuestion.value.firstType],
        tr: '',
        // 章节id为试卷id吗
        cid: route.query.id,
        ct: 'paperRecordPaperLibrary',
        cn: route.query.name,
        as: currentQuestion.value.answer,
        sn: currentQuestion.value.sign,
        t: new Date().getTime(),
        st: currentQuestion.value.stem

      }
    }).then(res => {
      if (res.data == true) {
        currentQuestion.value.collect = true
        currentQuestion.value.notedTime = new Date().getTime()
      }
      // QuestionApis.paperRecordsCollect(localStore.userSelectedIdsMap)
    })
  } else {
    QuestionApis.delCollect({
      industryCode: route.query.industryCode,
      examId: route.query.examId,
      categoryId: route.query.categoryId,
      // industryName: userStore.selectCategory.industryName,
      // examName: userStore.selectCategory.examName,
      // categoryName: userStore.selectCategory.categoryName,
      columnId: route.query.columnId,
      qid: currentQuestion.value.id,
    }).then(res => {
      if (res.success == true) {
        currentQuestion.value.collect = false
        currentQuestion.value.notedTime = 0
      }
    })
  }
}

function nextQuestion() {
  let current = currentQuestion.value.num
  if (current >= qCount.value) {
    return
  }
  currentQuestion.value.current = false;
  let aa = 0
  a:for (let i of questionData.value.content) {
    let b = 0;
    for (let j of i.qs) {
      if (j.num == current + 1) {
        currentIndex.value = [aa, b]
        j.current = true;
        break a;
      }
      b++
    }
    aa++
  }
}

function preQuestion() {
  let current = currentQuestion.value.num
  if (current <= 1) {
    return
  }
  currentQuestion.value.current = false;
  let aa = 0
  a:for (let i of questionData.value.content) {
    let b = 0;
    for (let j of i.qs) {
      if (j.num == current - 1) {
        currentIndex.value = [aa, b]
        j.current = true;
        break a;
      }
      b++
    }
    aa++
  }
}

async function saveAndExit() {
  if (loading.value) return;
  loading.value = true;
  // 保存请求
  // 权重lockAnswer>answer，循环一次(lockAnswer/answer)
  // 所有答案填完才能提交
  const commonData = {
        collectId: questionData.value.id,
        recordsType: 'paperRecordPaperLibrary',
        industryCode: route.query.industryCode,
        industryId: route.query.industryCode,
        examId: route.query.examId,
        categoryId: route.query.categoryId,
      }
  ;


  // data1已做，data2收藏，data3错题
  const data1 = {}, data2 = {}, removeIds = [], cdata = {}, data3 = {};

  let dc = 0, ec = 0, cc = 0;

  for (let item of questionData.value.content) {
    for (let q of item.qs) {
      // const cardItem = myAnswerCards.value[i]
      // const questionItem = questionList.value[i]
      let as;
      if (q.firstType == 4) {
        let arr = [];
        for (let i = 0; i < q.quOption.length; i++) {
          if (q['answer' + i]) {
            arr.push(q['answer' + i].trim())
          }
        }
        as = arr.join(' ')
      } else if (q.firstType == 3) {
        as = q.answer
      } else {
        if (q.answer instanceof Array) {
          as = JSON.stringify(q.answer)
        } else {
          as = q.answer
        }

      }
      if (q.answerStatus == 'done') {
        // 错题
        if (!q.isTrue) {
          data3[q.id] = {
            qid: q.id,
            qt: q.firstType,
            tr: '',
            as,
            sn: q.sign,
            ct: 'chapter',
            cid: route.query.chapterId,
            cn: route.query.name,
            t: q.time,
            st: q.stem
          }
          ec++;
        }
        dc++;
        data1[q.id] = {
          qid: q.id,
          qt: q.firstType,
          tr: '',
          as,
          sn: q.sign,
          t: q.time,
          rt: q.isTrue,
          newDo: !q.record,
          asb: q.answerBase64
        }
      }

      if (q.collect) {
        cc++;
        cdata[q.id] = q.notedTime
        data2[q.id] = {
          qid: q.id,
          qt: q.firstType,
          tr: '',
          as,
          sn: q.sign,
          ct: 'chapter',
          cid: route.query.chapterId,
          cn: route.query.name,
          t: q.notedTime,
          st: q.stem
        }
      } else {
        if (q.notedTime < 0) {
          removeIds.push(q.id)
        }
      }
    }
  }

  // 相较于上次的数量的增减
  dc -= Number(route.query.dc || 0)
  ec -= Number(route.query.ec || 0)
  cc -= ccNum.value
  let promiseArr = []

  // 保存试卷 QuestionApis.savePaper
  // 交卷QuestionApis.submitPaper

  // 需要添加收藏错题等吗？
  promiseArr.push(QuestionApis.submitPaper({
        industryCode: route.query.industryCode,
        examId: route.query.examId,
        categoryId: route.query.categoryId,
        recordsId: questionData.value.id,
        seconds: Number.parseInt((Date.now() - now) / 1000),
        imageCheck: false,
        ...signAndTimestamp(),
        data: data1
      }),
      QuestionApis.pushCollect({
        ...commonData,
        collectName: questionData.value.name,
        removeIds,
        cdata,
        data: data2
      }),
  )
  return Promise.all(promiseArr).then(res => {
    localStore.clearOneExamTime({
      paperId: route.query.id,
      recordsId: questionData.value.id
    });

    router.push({
      path: '/questionBank/paper/ExamResult',
      query: {
        id: res[0].data.paperRecords.id,
        industryCode: route.query.industryCode,
        examId: route.query.examId,
        categoryId: route.query.categoryId,
        paperId: route.query.id,
        columnId:route.query.columnId
      }
    })
  }).catch(_ => {
    ElMessage({
      message: '保存失败',
      type: 'error'
    })
  })
      .finally(_ => {
        loading.value = false;
        // 跳转结果页
      })
}

function doNote() {
//   用el-drawer
  common.value.setDraw(true)
//   获取笔记详情
  NoteApis.getNoteList({
    params: {
      type: 'paper',
      relationId: route.query.id,
      questionId: currentQuestion.value.id,
      categoryId: route.query.categoryId,
    }
  }).then(res => {
    if (res.data.length > 0) {
      common.value.noteAction = 'edit'
      common.value.setFormData(res.data[0])
    } else {
      common.value.noteAction = 'save'
    }
  })
}

function saveNote(formData) {
  if (common.value.noteAction == 'save') {
    NoteApis.publishNote({
      ...formData,
      type: 'paper',
      // 关联id就是章节id之类的
      relationId: route.query.id,
      // verify:'',
      questionId: currentQuestion.value.id,
      categoryId: route.query.categoryId,
    }).then(res => {
      common.value.setDraw(false)
      ElMessage({
        message: '笔记保存成功',
        type: 'success'
      })
    }).catch(_ => {
      ElMessage({
        message: '笔记保存失败',
        type: 'error'
      })
    })
  } else {
    NoteApis.updateNote({
      ...formData,
    }).then(res => {
      common.value.setDraw(false)
      ElMessage({
        message: '笔记更新成功',
        type: 'success'
      })
    }).catch(_ => {
      ElMessage({
        message: '笔记更新失败',
        type: 'error'
      })
    })
  }
}

function fillInput(val, index) {
  if (val) {
    currentQuestion.value.answerStatus = 'done'
  } else {
    const length = currentQuestion.value.quOption.length
    for (let i = 0; i < length; i++) {
      if (currentQuestion.value['answer' + i]) {
        currentQuestion.value.answerStatus = 'done'
        break
      }
    }


    currentQuestion.value.answerStatus = 'notDone';
    questionData.value.lastId = null
    // 清空则lastId为第一个做了的题或空
    a:for (let i of questionData.value.content) {
      for (let j of i.qs) {
        if (j.answerStatus == 'done') {
          questionData.value.lastId = j.id;
          break a;
        }
      }
    }

  }
}

function textareaChange(val) {
  if (val) {
    questionData.value.lastId = currentQuestion.value.id;
    currentQuestion.value.answerStatus = 'done'
  } else {
    currentQuestion.value.answerStatus = 'notDone';
    questionData.value.lastId = null
    // 清空则lastId为第一个做了的题或空
    a:for (let i of questionData.value.content) {
      for (let j of i.qs) {
        if (j.answerStatus == 'done') {
          questionData.value.lastId = j.id;
          break a;
        }
      }
    }
  }
}

function save(instance) {
//   01:59:44

// 没做就不保存了
  if (!questionData.value.lastId) {
    return Promise.resolve();
  }
  // 保存请求
  // 权重lockAnswer>answer，循环一次(lockAnswer/answer)
  // 所有答案填完才能提交
  const commonData = {
    // recordsType: 'paperRecordPaperLibrary',

    // chapterId: route.query.id,
    seconds: Number.parseInt((generatePaper.examTime * 60 * 1000 - instance) / 1000),
    cn: questionData.value.name,
    totalCount: qCount.value,

    recordsId: questionData.value.id,
    recordsType: 'paperRecordPaperLibrary',
    industryCode: route.query.industryCode,
    industryId: route.query.industryCode,
    examId: route.query.examId,
    categoryId: route.query.categoryId,
    lastId: questionData.value.lastId,

  };


  // data1已做，data2收藏，data3错题
  const data = {};
  for (let item of questionData.value.content) {
    for (let q of item.qs) {
      if (q.answerStatus == 'done') {
        let as;
        if (q.firstType == 4) {
          let arr = [];
          for (let i = 0; i < q.quOption.length; i++) {
            if (q['answer' + i]) {
              arr.push(q['answer' + i].trim())
            }
          }
          as = arr.join(' ')
        } else if (q.firstType == 3) {
          as = q.answer
        } else {
          if (q.answer instanceof Array) {
            as = JSON.stringify(q.answer)
          } else {
            as = q.answer
          }
        }
        data[q.id] = {
          as,
          rt: false,
          t: q.time
        }
      }
    }
  }


  return QuestionApis.savePaper({
    ...commonData,
    data
  }).finally(_ => {
    // loading.value = false;
  })
}

init()


</script>

<template>
  <div>
    <CommonQuestion ref="common" :qCount="qCount" :submitThis="submitThis" :currentOptionsStatus="currentOptionsStatus"
                    :change-current="changeCurrent"
                    :currentQuestion="currentQuestion"
                    :question-data="questionData" :loading="loading" :toggle="toggle"
                    :show-left="showLeft" :change-checkbox="changeCheckbox" :change-radio="changeRadio"
                    :next-question="nextQuestion" :pre-question="preQuestion" :toggle-note="toggleNote"
                    :save-and-exit="saveAndExit" :do-note="doNote" :save-note="saveNote" paper-mode="exam"
                    :fill-input="fillInput" :textarea-change="textareaChange" :exam-time="examTime" :save="save"/>
  </div>
</template>

<style scoped>

</style>